import React, { useEffect } from 'react';

import { getUserId } from '@/entities/auth/model/selectors';
import { CourseCardLoader, OrderCard, productApi } from '@/entities/course';
import { innerUrls } from '@/shared/constants';
import { makeMockArray } from '@/shared/lib/transformArrayIntoObject';
import { useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, Grid } from '@/shared/ui';

import { NothingFound } from '../../NothingFound';
import cs from './Purchases.module.scss';

export const Purchases = () => {
  const userId = useAppSelector(getUserId);
  const { data: orders, isLoading } = productApi.useGetOrdersQuery(
    { 'filters[userId]': userId ?? undefined, 'orderBy[createdAt]': 'DESC' },
    { skip: !userId },
  );
  useEffect(() => {
    const placeholder = document.getElementsByClassName('Placeholder_container__TD4MH')[0];
    if (placeholder) {
      (placeholder as HTMLElement).style.marginTop = '0px';
      (placeholder as HTMLElement).style.gap = '22px';
    }
  }, []);
  return (
    <div className={cs.block}>
      {!isLoading && !!orders?.orders?.length && (
        <Grid otherGap size="l">
          {orders?.orders.map((item) => (
            <OrderCard
              attachments={item.items[0].product.course.attachments}
              createdAt={item?.createdAt}
              id={item?.id}
              key={item?.createdAt}
              src={item?.items[0].product.image}
              title={item?.items[0].title}
            />
          ))}
        </Grid>
      )}
      {isLoading && (
        <Grid otherGap size="l">
          {makeMockArray(4).map(({ id }) => (
            <CourseCardLoader key={id} />
          ))}
        </Grid>
      )}
      {!isLoading && orders?.orders?.length === 0 && (
        <div className={cs.no_purchases}>
          <NothingFound />

          <Button
            className={cs.btn}
            data-testid="link-catalog"
            href={innerUrls.catalog}
            link
            variant={ButtonVariants.Primary}
          >
            Перейти к выбору
          </Button>
        </div>
      )}
    </div>
  );
};
